import re
from google.appengine.api import users,images
from google.appengine.ext import db
from string import capitalize,replace,lower,strip,capwords

def normalize(value):
	key=re.sub(r"\W+","",re.sub(r"\s{1,}","_",lower(strip(value))))
	if len(key)>0:
		return key
	else:
		return None

def denormalize(value):
	return replace(capitalize(str(value)),"_"," ")
	
def denormalize_questions(questions):
	return denormalize('? '.join(questions))

def denormalize_answers(answers):
	return denormalize(', '.join(answers))
	
def strip_email(email):
	return email.partition("@")[0]

def nickname(user_id):
	if user_id:
		s=db.Model.get(db.Key.from_path('Settings',user_id))
		if s:
			if s.nickname:
				return capwords(s.nickname)
			else:
				return capwords(strip_email(s.user.nickname()))
	return user_id

def describe(thing):
	return denormalize(', '.join(thing.answers))

def photo(key):
	return images.get_serving_url(str(key),size=350)

def thumbnail(key):
	return images.get_serving_url(str(key),size=48)

def gravatar(email):
	import urllib,hashlib
	gravatar_url="http://www.gravatar.com/avatar/"+hashlib.md5(email.lower()).hexdigest()+"?"
	gravatar_url+=urllib.urlencode({'d':'mm','s':'24'})
	return gravatar_url
	
def answer_or_ask(is_owner):
	if is_owner:
		return 'answer'
	else:
		return 'ask'

def skip_or_delete(answered):
	if answered:
		return 'delete'
	else:
		return 'skip'